<?php
/**
* 多主题插件
*
* MultiThemes for Z-BlogPHP
*
* @author      心扬<chrisyoungpark@qq.com>
* @version     1.0
*/

// 注册插件
RegisterPlugin('MultiThemes', 'ActivePlugin_MultiThemes');

/**
 * 挂载系统接口
 */
function ActivePlugin_MultiThemes()
{
    global $zbp; //使用变量$zbp前应进行全局声明

    /*
    * 检查冲突
    * 若冲突的插件已启用，则终止插件
    * 目前已知冲突的插件(ID)有：2themes,Pad，wthemes
    */
    if ($zbp->CheckPlugin('2themes') || $zbp->CheckPlugin('Pad') || $zbp->CheckPlugin('wthemes'))
        return;

    Add_Filter_Plugin('Filter_Plugin_Index_Begin', 'Before_View_MultiThemes');  //首页显示前预处理钩子
    Add_Filter_Plugin('Filter_Plugin_Search_Begin', 'Before_View_MultiThemes'); //搜索页显示前预处理钩子
    Add_Filter_Plugin('Filter_Plugin_Admin_TopMenu', 'TopMenu_MultiThemes');    //管理后台右上方菜单钩子
}

/**
 * 首页与搜索页钩子
 */
function Before_View_MultiThemes()
{
    global $zbp;

    $clients = $zbp->Config('MultiThemes')->clients; //获取客户端主题配置
    $config  = $zbp->Config('MultiThemes')->config;  //获取插件配置

    if (is_numeric($multitheme_id = GetVars('mtid', 'GET'))) { //优先检测URL
        if (!array_key_exists($multitheme_id, $clients)) { //验证范围
            $multitheme_id = 1;
        } else {
            unset($_COOKIE["mtid"]);
            setcookie("mtid", $multitheme_id, time()+60*60*24*30); //写入COOKIE，默认保存一个月
        }
    } elseif ($multitheme_id = GetVars('mtid', 'COOKIE')) { //检测COOKIES
        if (!is_numeric($multitheme_id) || !array_key_exists($multitheme_id, $clients))  //验证范围
            $multitheme_id = 1;
    } elseif ($config[0]) { //检测USER_AGENT
        $multitheme_id = ClientDetector_MultiThemes($config[1], $config[2]);
        setcookie("mtid", $multitheme_id, time()+60*60*24*30);
    } else {
        $multitheme_id = 1; //默认PC
    }
    //切换主题
    InitializtionTheme_MultiThemes($clients[$multitheme_id][0], $clients[$multitheme_id][1]);
}

/**
 * 客户端检测
 * @param int $d_Android  是否检测安卓系统
 * @param int $d_iOS      是否检测iOS系统
 * @return int $client_id
 */
function ClientDetector_MultiThemes($d_Android, $d_iOS)
{
    // Composer Autoload
    require __DIR__ . '/vendor/autoload.php';
    $detect = new Mobile_Detect;

    $client_id = 1; //默认PC

    if ($detect->isTablet())
        $client_id = 3;
    if ($detect->isMobile())
        $client_id = 2;
    if($d_Android && $detect->isAndroidOS())
        $client_id = 4;
    if ($d_iOS && $detect->isiOS())
        $client_id = 5;

    return $client_id;
}

/**
 * 初始化主题，实现主题切换
 * 
 * 此函数是整个插件的核心，如果你有更好的实现方案，欢迎联系我进行交流！
 * 
 * @param string $theme 主题id
 * @param string $style 样式文件名（不含后缀）
 */
function InitializtionTheme_MultiThemes($theme, $style)
{
    global $zbp;
    
    $zbp->option['ZC_BLOG_THEME'] = $theme;
    $zbp->option['ZC_BLOG_CSS']   = $style;

    //处理主题函数
    if (is_readable($include_file = ZBP_PATH . 'zb_users/theme/' . $theme . '/include.php')) {
        if (isset($GLOBALS['plugins'][$theme])) { //判断是否已经定义插件函数
            $func_name = $GLOBALS['plugins'][$theme];
        } else {
            include $include_file; //引入主题 include.php 文件
            $func_name = $GLOBALS['plugins'][$theme];
        }
        if (function_exists($func_name)) 
            $func_name(); //执行主题自定义函数
    }
    //加载模板类
    $zbp->template = $zbp->PrepareTemplate();
}

/**
 * 管理页面右上方添加设置按钮
 */
function TopMenu_MultiThemes(&$topmenus)
{
    global $zbp;
    $topmenus[] = MakeTopMenu("root", "多主题设置", $zbp->host. "zb_users/plugin/MultiThemes/main.php#tabs=mt_pc","","");
}

/**
 * 插件安装激活时执行函数
 */
function InstallPlugin_MultiThemes()
{
    global $zbp;

    // 初始化配置
    $zbp->Config('MultiThemes')->clients = array( //客户端主题配置
        1 => array('default', 'default'), //桌面pc （为了和主题名相匹配，数组键从1开始）
        2 => array('default', 'default'), //手机mobi
        3 => array('default', 'default'), //平板tablet
        4 => array('default', 'default'), //安卓Android
        5 => array('default', 'default')  //苹果iOS
    );

    $zbp->Config('MultiThemes')->config = array( //插件配置
        0 => 1, //是否启用客户端UserAgent检测，默认为1启用(0关闭)
        1 => 1, //是否启用安卓Android客户端检测，默认为1启用(0关闭)
        2 => 1  //是否启用苹果iOS客户端检测，默认为1启用(0关闭)
    );

    $zbp->Config('MultiThemes')->tabname = array( //配置页面tab名称
        0 => '主题一',
        1 => '主题二',
        2 => '主题三',
        3 => '主题四',
        4 => '主题五'
    );
    //保存配置
    $zbp->SaveConfig('MultiThemes');
}

/**
 * 插件卸载时执行函数
 */
function UninstallPlugin_MultiThemes()
{
    global $zbp;

    // 删除配置
    if ($zbp->HasConfig('MultiThemes')) {
        $zbp->DelConfig('MultiThemes');
    }
}
